//
//  SNEquipmentViewController.m
//  project
//
//  Created by 黄建华 on 2017/11/20.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNEquipmentViewController.h"
#import "CameraViewController.h"
#import "FindBlueViewController.h"
#import "DeviceSetViewController.h"
#import "HealthSetViewController.h"
#import "ScheduleViewController.h"
#import "AlarmViewController.h"
#import "MessagePushViewController.h"
#import "FindBandView.h"
#import "SNEquipmentScreenViewController.h"
@interface SNEquipmentViewController ()

@property (nonatomic, strong) UILabel      *titleLabel;
@property (nonatomic, strong) UIImageView  *powerImage;
@property (nonatomic, strong) UIImageView  *showPower;
@property (nonatomic, strong) UILabel      *macLabel;
@property (nonatomic, strong) UIImageView *animateView;
@property (nonatomic, strong) UIView      *bgView;
@property (nonatomic, strong) UILabel     *powerLabel;
@property (nonatomic, strong) UIButton    *setBtn;
@property (nonatomic, strong) UIImageView *backImageView;
@end

@implementation SNEquipmentViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    //    [[UIView appearance] setTintColor:[UIColor clearColor]];
    if ([APPFIRST getBOOLValue]) {
        if (!KK_BLEConnect.centerPowerOn) {
            SHOWMBProgressHUD(nil, SN_Text(@"检测到你的手机蓝牙功能未启用，请前往手机的[设置]启用蓝牙功能"), nil, NO, 2.0);
        }
        [APPFIRST setBOOLValue:NO];
    }
    
    [self performSelector:@selector(refreshView) withObject:nil afterDelay:0.1];
    
    if (!IOSSHOWTARBARACTIVE) {
        return;
    }
    NSInteger width = 0;
    if (KK_ShareData.lastVcTag > KK_ShareData.currentVCTag) {
        width = HHHWIDTH;
    }
    if (KK_ShareData.lastVcTag < KK_ShareData.currentVCTag) {
        width = -HHHWIDTH;
    }
    
    if (KK_ShareData.lastVcTag == KK_ShareData.currentVCTag) {
        width = 0;
    }
    if (width != 0) {
        if (_bgView) {
            [_bgView removeFromSuperview];
            _bgView = nil;
        }
        if (_animateView) {
            [_animateView removeFromSuperview];
            _animateView = nil;
        }
        
        _animateView = [[UIImageView alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_animateView];
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(HHHWIDTH, HHHHEIGHT), NO, 0.0);
        [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        _animateView.image = viewImage;
        
        _bgView                 = [[UIView alloc] initWithFrame:self.view.frame];
        _bgView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_bgView];
        [self.view bringSubviewToFront:_animateView];
        _animateView.frame  = SNFRAME(width, 0, HHHWIDTH, HHHHEIGHT);
        _animateView.hidden = NO;
        _bgView.hidden      = NO;
        DEF_WEAKSELF_(SNEquipmentViewController)
        [UIView animateWithDuration: VIEWANIMATETIME animations:^{
            _animateView.frame = SNFRAME(0, 0, HHHWIDTH, HHHHEIGHT);
        } completion:^(BOOL finished) {
            _animateView.hidden = YES;
            _bgView.hidden = YES;
            [weakSelf loadBleView];
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshCurrentView) object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addHeadeView];
    NSArray *imageArr = @[];
    NSArray *titleArr = @[];
    if (SN_USER.wallpaper) {
        imageArr = @[@"",@"shebei_icon_ghpm",@"",@"相机(1)", @"搜索", @"健康", @"日程(1)", @"闹钟(1)", @"推送"];
        titleArr = @[@"",HHH_Text(@"更换壁纸"),@"",HHH_Text(@"远程相机"), HHH_Text(@"查找手环"), HHH_Text(@"健康提醒"), HHH_Text(@"日程管理"), HHH_Text(@"闹钟"), HHH_Text(@"推送")];
        [self addBottomViewTitle:titleArr imageArray:imageArr];
    } else {
        imageArr = @[@"相机(1)", @"搜索", @"健康", @"日程(1)", @"闹钟(1)", @"推送"];
        titleArr = @[HHH_Text(@"远程相机"), HHH_Text(@"查找手环"), HHH_Text(@"健康提醒"), HHH_Text(@"日程管理"), HHH_Text(@"闹钟"), HHH_Text(@"推送")];
        [self addBottomViewTitle:titleArr imageArray:imageArr];
    }
}

- (void)dealloc {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshCurrentView) object:nil];
}

- (void)refreshCurrentView {
    if (!_setBtn) {
        _setBtn       = [UIButton buttonWithType:UIButtonTypeCustom];
        _setBtn.frame = CGRectMake(HHHWIDTH-44-10, 20+FitSimpleIpx(0, 20)+5, 44, 44);
        if (KK_BLEConnect.model.isConnected) {
            [_setBtn setImageNormal:@"设置2"];
        }
        [_setBtn addTouchUpTarget:self action:@selector(pushToSetVC:)];
        [self.view addSubview:_setBtn];
    }
    if (KK_BLEConnect.model.isConnected) {
        [self loadBleView];
    }
}

- (void)loadBleView {
    _powerLabel.hidden = YES;
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            if (view.tag >= 100 && view.tag <= 106) {
                view.hidden = YES;
            }
        }
        if ([view isKindOfClass:[UILabel class]]) {
            if (view.tag >= 100 && view.tag <= 106) {
                view.hidden = YES;
            }
        }
    }
    
    if (TARGET_IPHONE_SIMULATOR) {
        [self showDeviceVc];
        _setBtn.hidden = NO;
        [_setBtn setImageNormal:@"设置2"];
        return;
    }
    
    if (!KK_BLEConnect.model.isConnected || !KK_BLEConnect.centerPowerOn) { // 手环绑定界面
        FindBlueViewController *findVC = [[FindBlueViewController alloc]init];
        [self.navigationController pushViewController:findVC animated:NO];
        NSLog(@"蓝牙未绑定或者没有打开蓝牙功能>>>>>>");
        _setBtn.hidden = YES;
    } else {
        [self showDeviceVc];
        _setBtn.hidden = NO;
        [_setBtn setImageNormal:@"设置2"];
    }
}

- (void)addHeadeView {
    UIImage     *backImage     = UIImageNamed(@"背景");
    _backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), HHHWIDTH, HHHWIDTH*backImage.size.height/backImage.size.width)];
    
    _backImageView.userInteractionEnabled = YES;
    _backImageView.image                  = backImage;
    [self.view addSubview:_backImageView];
    
    _titleLabel               = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), HHHWIDTH, 44)];
    _titleLabel.text          = @"";
    _titleLabel.font          = SNFONT(18.);
    _titleLabel.textColor     = [UIColor whiteColor];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_titleLabel];
    
    _setBtn       = [UIButton buttonWithType:UIButtonTypeCustom];
    _setBtn.frame = CGRectMake(HHHWIDTH-44-10, 20+FitSimpleIpx(0, 20)+5, 44, 44);
    if (KK_BLEConnect.model.isConnected) {
        [_setBtn setImageNormal:@"设置2"];
    }
    [_setBtn addTouchUpTarget:self action:@selector(pushToSetVC:)];
    [self.view addSubview:_setBtn];
    
    _powerLabel               = [[UILabel alloc]initWithFrame:CGRectMake(FitW(20), _backImageView.height*0.332, HHHWIDTH-FitW(20), FitH(25))];
    _powerLabel.textAlignment = NSTextAlignmentLeft;
    _powerLabel.font          = SNFONTMIN(15);
    _powerLabel.text          = SN_Text(@"当前电量");
    _powerLabel.textColor     = [UIColor whiteColor];
    CGSize titleSize = [_powerLabel.text sizeWithFont:_powerLabel.font maxSize:CGSizeMake(MAXFLOAT, FitH(25))];
    _powerLabel.size = titleSize;
    [self.view addSubview:_powerLabel];
    
    _powerImage = [[UIImageView alloc]initWithFrame:CGRectMake(_powerLabel.right +3, _powerLabel.centerY - 30/2, 40, 30)];
    _powerImage.image = [UIImage imageNamed:@"icon_electricity_lv1"];
    [self.view addSubview:_powerImage];
    
    _showPower = [[UIImageView alloc] initWithFrame:CGRectMake(5,10, _powerImage.width-11, _powerImage.height-20)];
    _showPower.backgroundColor = [UIColor whiteColor];
    
    [_powerImage addSubview:_showPower];
    
    _macLabel               = [[UILabel alloc]initWithFrame:CGRectMake(FitW(20), _powerImage.origin.y +35, HHHWIDTH-FitW(20), FitH(20))];
    _macLabel.textAlignment = NSTextAlignmentLeft;
    _macLabel.font          = SNFONTMIN(15);
    _macLabel.textColor     = [UIColor whiteColor];
    [self.view addSubview:_macLabel];
}

- (void)addBottomViewTitle:(NSArray *)titleArr imageArray:(NSArray *)imageArr {
    
    CGFloat width     = (HHHWIDTH-FitW(20))/3;
    CGFloat y         = _backImageView.bottom;
    
    for (int i = 0; i < titleArr.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(FitW(10)+width*(i%3), y+width*(i/3), width, width);
        btn.tag   = 100+i;
        [btn setImageNormal:imageArr[i]];
        [btn addTouchUpTarget:self action:@selector(btnClick:)];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, width-FitH(23), width, FitH(20))];
        label.tag           = 1000 +i;
        label.text          = titleArr[i];
        label.font          = [UIFont systemFontOfSize:FitFont(14)];
        label.textColor     = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        [btn addSubview:label];
        
        [self.view addSubview:btn];
    }
}

- (void)btnClick:(UIButton *)sender {
    sender.enabled = NO;
    
    if (SN_USER.wallpaper) {
        if (sender.tag == 100 || sender.tag == 102) {
            // 空余的按钮
        }else if (sender.tag == 101) {
            SNEquipmentScreenViewController *vc = [[SNEquipmentScreenViewController alloc]init];
            CustomTabBar         *tabBar   = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:vc animated:YES];
        } else if (sender.tag == 103) {
            CameraViewController *cameraVC = [[CameraViewController alloc]init];
            [self.navigationController pushViewController:cameraVC animated:YES];
        } else if (sender.tag == 104) {
            FindBandView *findBandView = [[FindBandView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, HHHHEIGHT)];
            [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:findBandView];
            [findBandView animationUp];
            [KK_BLESend sendSetFindBle:YES withUpdateBlock:^(id object, KKBLEAcceptType type)
             {
             }];
        } else if (sender.tag == 105) {
            HealthSetViewController *healthVC = [[HealthSetViewController alloc]init];
            CustomTabBar            *tabBar   = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:healthVC animated:YES];
        } else if (sender.tag == 106) {
            ScheduleViewController *scheduleVC = [[ScheduleViewController alloc]init];
            CustomTabBar           *tabBar     = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            [self.navigationController pushViewController:scheduleVC animated:YES];
        } else if (sender.tag == 107) {
            AlarmViewController *alarmVC = [[AlarmViewController alloc]init];
            CustomTabBar        *tabBar  = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:alarmVC animated:YES];
        } else if (sender.tag == 108) {
            MessagePushViewController *pushVC = [[MessagePushViewController alloc]init];
            CustomTabBar              *tabBar = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:pushVC animated:YES];
        }
    } else {
        if (sender.tag == 100) {
            CameraViewController *cameraVC = [[CameraViewController alloc]init];
            CustomTabBar         *tabBar   = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:cameraVC animated:YES];
        } else if (sender.tag == 101) {
            FindBandView *findBandView = [[FindBandView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, HHHHEIGHT)];
            [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:findBandView];
            [findBandView animationUp];
            [KK_BLESend sendSetFindBle:YES withUpdateBlock:^(id object, KKBLEAcceptType type)
             {
             }];
        } else if (sender.tag == 102) {
            HealthSetViewController *healthVC = [[HealthSetViewController alloc]init];
            CustomTabBar            *tabBar   = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:healthVC animated:YES];
        } else if (sender.tag == 103) {
            ScheduleViewController *scheduleVC = [[ScheduleViewController alloc]init];
            CustomTabBar           *tabBar     = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            [self.navigationController pushViewController:scheduleVC animated:YES];
        } else if (sender.tag == 104) {
            AlarmViewController *alarmVC = [[AlarmViewController alloc]init];
            CustomTabBar        *tabBar  = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:alarmVC animated:YES];
        } else if (sender.tag == 105) {
            MessagePushViewController *pushVC = [[MessagePushViewController alloc]init];
            CustomTabBar              *tabBar = (CustomTabBar *)self.tabBarController;
            [tabBar hiddenTheTabBarView];
            [self.navigationController pushViewController:pushVC animated:YES];
        }
    }
    sender.enabled = YES;
}

- (void)pushToSetVC:(UIButton *)sender {
    sender.enabled = NO;
    DeviceSetViewController *deviceVC = [[DeviceSetViewController alloc]init];
    CustomTabBar            *tabBar   = (CustomTabBar *)self.tabBarController;
    [tabBar hiddenTheTabBarView];
    [self.navigationController pushViewController:deviceVC animated:YES];
    sender.enabled = YES;
}

- (void)refreshView {
    [self loadBleView];
}

- (void)showDeviceVc {
    // 设备界面
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            if (view.tag >= 100 && view.tag <= 106) {
                view.hidden = NO;
            }
        }
        if ([view isKindOfClass:[UILabel class]]) {
            if (view.tag >= 100 && view.tag <= 106) {
                view.hidden = NO;
            }
        }
    }
    _powerLabel.hidden = NO;
    _titleLabel.text   = [NSString stringWithFormat:@"%@ %@", SN_Text(@"已连接"), KK_BLEModel.bleName ? KK_BLEModel.bleName : @""];
    [self showImageWithPowerValue:SN_USER.bleBatteryQuantity];
    
    NSString *macString = [KK_BLELastDeviceMac getObjectValue];
    if (macString.length > 0) {
        _macLabel.text = [NSString stringWithFormat:@"MAC: %@", [macString uppercaseString]];
    } else {
        _macLabel.text = [NSString stringWithFormat:@"MAC: %@", KK_BLEModel.bleMAC.uppercaseString ? KK_BLEModel.bleMAC.uppercaseString : @""];
    }
    [KK_BLESend sendGetDeviceBasicInfoWithUpdate:^(id object, KKBLEAcceptType type) {
    }];
    if ([UIApplication sharedApplication].applicationIconBadgeNumber > 0) {
        for (UIButton *btn in self.view.subviews) {
            if (btn.tag == 103) {
                UIButton *badge = [UIButton buttonWithType:UIButtonTypeCustom];
                badge.frame              = CGRectMake(btn.width*0.7, btn.height *0.25, 20, 20);
                badge.layer.cornerRadius = 10;
                badge.clipsToBounds      = YES;
                badge.backgroundColor    = [UIColor redColor];
                badge.titleNormal        = [NSString stringWithFormat:@"%ld", [UIApplication sharedApplication].applicationIconBadgeNumber];
                badge.titleColorNormal   = [UIColor whiteColor];
                [btn addSubview:badge];
            }
        }
    } else {
        for (UIButton *btn in self.view.subviews) {
            if (btn.tag == 103) {
                for (UIControl *view in btn.subviews) {
                    if ([view isKindOfClass:[UIButton class]]) {
                        [view removeFromSuperview];
                    }
                }
            }
        }
    }
}

- (void)updateModel:(KKBLEModel *)model type:(KKBLEUpdateType)type {
    if (!KK_BLEConnect.model.isConnected) { // 手环绑定界面
        FindBlueViewController *findVC = [[FindBlueViewController alloc]init];
        [self.navigationController pushViewController:findVC animated:NO];
    }
    
    if (type == KKBLEUpdateDidConnect) {
        [self loadBleView];
        _setBtn.hidden = NO;
        [_setBtn setImageNormal:@"设置2"];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(refreshCurrentView) object:nil];
        [self performSelector:@selector(refreshCurrentView) withObject:nil afterDelay:5.0];
    }
    if (type == KKBLEUpdatePowerOn) {
        SHOWMBProgressHUD(SN_Text(@"蓝牙开启..."), nil, nil, NO, 2.0);
    }
}

// 通知界面接收数据刷新相应界面的UI UpdateUiType
- (void)updateView:(KKBLEAcceptType)type {
    if (type == KKBLEAcceptTypeDevideInfo) {
        //        NSLog(@"设备界面更新设备信息>>>>>");
        [self showImageWithPowerValue:SN_USER.bleBatteryQuantity];
        _titleLabel.text   = [NSString stringWithFormat:@"%@ %@", SN_Text(@"已连接"), KK_BLEModel.bleName ? KK_BLEModel.bleName : @""];
        _powerLabel.hidden = NO;
    }
    if (type == KKBLEAcceptTypeDevideMAC) {
        _macLabel.text = [NSString stringWithFormat:@"MAC: %@", KK_BLEModel.bleMAC.uppercaseString ? KK_BLEModel.bleMAC.uppercaseString : @""];
    }
}

- (UIImage *)showImageWithPowerValue:(NSInteger)value {
    UIImage *image;
    CGFloat width = _powerImage.width - 11;
    CGFloat height = _powerImage.height - 20;
    
    CGFloat valueWidth = (1.0 *value/100)*width;
    _showPower.frame = CGRectMake(5,10,valueWidth,height);
    
    if (KK_BLEModel.fullPower >0 ) {
        CGFloat valueWidth = (1.0*width/KK_BLEModel.fullPower)*KK_BLEModel.currentPower;
        _showPower.frame = CGRectMake(5,10,valueWidth,height);
    }
    
    return image;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

